import { defineStore } from "pinia";
import { store } from "@/store";
import { userType } from "./types";
//import { routerArrays } from "@/layout/types";
import { router, resetRouter } from "@/router";
import { storageSession } from "@pureadmin/utils";
import { getLogin, refreshTokenApi } from "@/api/user";
import { UserResult, RefreshTokenResult } from "@/api/user";
//import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import { type DataInfo, setToken, removeToken, sessionKey } from "@/utils/auth";
import { loginByYunHua } from "@/api/system";

export const useUserStore = defineStore({
  id: "pure-user",
  state: (): userType => ({
    loginUrl:
      storageSession().getItem<DataInfo<number>>(sessionKey)?.loginUrl ?? "",
    userHeader:
      storageSession().getItem<DataInfo<number>>(sessionKey)?.userHeader ?? "",
    userNiChen:
      storageSession().getItem<DataInfo<number>>(sessionKey)?.userNiChen ?? "",
    // 用户名
    userAccount:
      storageSession().getItem<DataInfo<number>>(sessionKey)?.userAccount ?? "",
    //用户id
    userId:
      storageSession().getItem<DataInfo<number | string>>(sessionKey)?.userId ??
      "",
    // 页面级别权限
    roles: storageSession().getItem<DataInfo<number>>(sessionKey)?.roles ?? [],
    isAdmin:
      storageSession().getItem<DataInfo<boolean>>(sessionKey)?.isAdmin ?? false,
    //看板对应的APPID
    appID: storageSession().getItem<DataInfo<boolean>>(sessionKey)?.appID ?? 0,
    //看板对应的appName
    appName:
      storageSession().getItem<DataInfo<boolean>>(sessionKey)?.appName ?? "",
    dvID: storageSession().getItem<DataInfo<boolean>>(sessionKey)?.dvID ?? 0,
    appInfoForm:
      storageSession().getItem<DataInfo<boolean>>(sessionKey)?.appInfoForm ??
      null,
    companyID:
      storageSession().getItem<DataInfo<number>>(sessionKey)?.companyID ?? 0,
    aiFalg: storageSession().getItem<DataInfo<number>>(sessionKey)?.aiFalg ?? 0,
    comID: storageSession().getItem<DataInfo<number>>(sessionKey)?.comID ?? ""
  }),
  actions: {
    SET_COMPANYID(companyID: number) {
      this.companyID = companyID;
    },
    SET_COMID(comID: string) {
      this.comID = comID;
    },
    SET_AIFALG(aiFalg: number) {
      this.aiFalg = aiFalg;
    },
    /** 存储用户名 */
    SET_USERNAME(userAccount: string) {
      this.userAccount = userAccount;
    },
    SET_ISADMIN(iserAdmin: boolean) {
      this.isAdmin = iserAdmin;
    },
    /** 存储角色 */
    SET_ROLES(roles: Array<string>) {
      this.roles = roles;
    },
    //存储id
    SET_ID(userId: string | number) {
      this.userId = userId;
    },
    SET_USERHEADER(userHeader: string) {
      this.userHeader = userHeader;
    },
    SET_USERNICHENG(userNicheng: string) {
      this.userNiChen = userNicheng;
    },
    SET_LOGINURL(loginUrl: string) {
      this.loginUrl = loginUrl;
    },
    SET_APPID(appid: number) {
      this.appID = appid;
    },
    SET_APPNAME(appname: string) {
      this.appName = appname;
    },
    SET_DVID(dvid: number) {
      this.dvID = dvid;
    },
    SET_APPINFOFOM(form: any) {
      this.appInfoForm = form;
    },
    /** 登入 */
    async loginByUsername(data) {
      return new Promise<UserResult>((resolve, reject) => {
        getLogin(data)
          .then(data => {
            if (data.success) {
              setToken(data.data);
              resolve(data);
            } else {
              resolve(data);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    async loginByYunHuaPage(data) {
      return new Promise<UserResult>((resolve, reject) => {
        loginByYunHua(data)
          .then(data => {
            if (data.success) {
              setToken(data.data);
              resolve(data);
            } else {
              resolve(data);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    /** 前端登出（不调用接口） */
    logOut() {
      this.userAccount = "";
      this.roles = [];
      removeToken();
      resetRouter();
      location.reload();
      router.push("/login");
      //console.log("path", path)
      //router.push("http://www.baidu.com");
    },
    /** 刷新`token` */
    async handRefreshToken(data) {
      return new Promise<RefreshTokenResult>((resolve, reject) => {
        refreshTokenApi(data)
          .then(data => {
            if (data) {
              setToken(data.data);
              resolve(data);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    }
  }
});

export function useUserStoreHook() {
  return useUserStore(store);
}
